package com.zhuangjie.security.provider;

import com.zhuangjie.security.helper.JwtHelper;
import com.zhuangjie.security.helper.config.td.AllTokenDataKeys;
import com.zhuangjie.security.intercepor.UserRequestInterceptor;
import com.zhuangjie.security.utils.JwtUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author zhuangjie
 * @date 2023/09/21
 */
public class UserProvider {
    public static<T> T currentUserIdUseType(Class<T> clazz) {
        T value = getAttribute(AllTokenDataKeys.USER_ID_KEY, clazz);
        if (value == null) {
            throw new RuntimeException("无法从上下文中获取到登录用户id");
        }
        return value;
    }
    public static Long currentUserId() {
        return currentUserIdUseType(Long.class);
    }

    public static Object currentUserIdUseType() {
        return currentUserIdUseType(Object.class);
    }
    public static List<String> currentUserRoles() {
        List value = getAttribute(AllTokenDataKeys.ROLES_KEY, List.class);
        if (value == null) {
            return new ArrayList<>();
        }
        return (List<String>)value;
    }
    protected static <T> T getAttribute(String attributeName, Class<T> clazz) {
        Map<String, Object> tokenData = UserRequestInterceptor.threadLocal.get();

        if (tokenData == null) {
            // 如果没有tokenData，尝试从请求头中解析出来token再解析为tokenData来使用
            String token = JwtHelper.getTokenFromAuthorizationHeader();
            if (token != null) {
                try {
                    tokenData = JwtUtils.checkToken(token);
                } catch (Exception ignored) {
                }
            }
        }
        if (tokenData != null) {
            Object value = tokenData.get(attributeName);
            if (clazz.isInstance(value)) {
                return clazz.cast(value);
            }
        }
        return null;
    }
}